"use strict";

import Vue from "vue";
import axios from "axios"; // 引入配置文件
import myConfig from "@/assets/js/config";

import { MessageBox } from "element-ui";
import toolClass from "@/assets/js/toolClass";
import router from "../router/index";
// axios.defaults.baseURL = myConfig.fileCtx;
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.common['Authorization'] =config.token;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
let config = {
  baseURL: myConfig.ctx
};

const _axios = axios.create(config);

_axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';

var stateTime = false;
_axios.interceptors.request.use(
  function (config) {
    var token = myConfig.token || toolClass.getCookie("xinyun-front-token");
    let userId = ""
    if (toolClass.getCookie("xinyun-front-userInfo")) {
      userId = JSON.parse(toolClass.getCookie("xinyun-front-userInfo")).userId
    } else {
      userId = ""
    }
    if (token) {
      config.headers["Authorization"] = token;
      config.headers["appId"] = myConfig.appId;
      config.headers["timestamp"] = new Date().valueOf();
      config.headers["sign"] = toolClass.sign(config.url, new Date().valueOf());
      config.headers["userId"] = userId;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

_axios.interceptors.response.use(
  function (response) {
    if (response) {
      if (response.data && response.data.retCode && response.data.retCode == "00000") {
        return response.data;
      } else if (response.data && response.data.retCode && response.data.retCode == "71800") {
        return response.data;
      } else {
        MessageBox.alert(response.data.retInfo, "提示", {
          type: "error",
          duration: 5 * 1000
        });
      }
    }
  },
  function (error) {
    // Do something with response error
    if (error) {
      switch (error.response.status) {
        case 404:
          MessageBox.alert("请求url错误：" + error.response.data.path, "提示", {
            type: "error",
            duration: 5 * 1000
          });
          break;
        case 500:
          MessageBox.alert("系统错误：" + error.response.data.message, "提示", {
            type: "error",
            duration: 5 * 1000
          });
          break;
        case 400:
          MessageBox.alert("请求参数错误：" + error.response.data.message, "提示", {
            type: "error",
            duration: 5 * 1000
          });
          break;
        case 401:
          if (!stateTime) {
            MessageBox.alert("用户信息认证失败或登录超时，请重新登录！", "提示", {
              type: "error",
              duration: 5 * 1000
            });
            let axiosSource = axios.CancelToken.source();
            axiosSource.cancel("取消请求");
            toolClass.delCookie("xinyun-front-token");
            // toolClass.delCookie("xinyun-userInfoData");
            router.push({
              path: "/home",
              query: {
                openLogin: true
              }
            });
            setTimeout(() => {
              stateTime = false;
            }, 3000);
            stateTime = true;
          }
          break;
      }
    }
    return Promise.reject(error);
  }
);

Plugin.install = function (Vue) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $http: {
      get() {
        return _axios;
      }
    }
  });
};

Vue.use(Plugin);

export default Plugin;
